<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="公示类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
              <j-dict-select-tag type="list" v-model="model.type" dictCode="public_info_type" placeholder="请选择公示类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item :label="model.type != 3?'名称':'姓名'" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="title">
              <a-input v-model="model.title" :maxLength="model.type != 3?100:10" :placeholder="`请输入${model.type != 3?'名称':'姓名'}`"></a-input>
            </a-form-model-item>
          </a-col>
          <div v-if="model.type != 3">
            <a-col :span="24" >
              <a-form-model-item label="内容" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="content">
                <j-editor v-model="model.content" :disabled="formDisabled"/>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="附件" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                <a-upload
                  :multiple="true"
                  :fileList="fileList"
                  name="file"
                  :before-upload="beforeUpload"
                  :showUploadList="{showRemoveIcon:formDisabled?false:true}"
                  :remove="onRemove"
                >
                  <a-button> <a-icon type="upload" /> 点击上传 </a-button>
                </a-upload>
              </a-form-model-item>
            </a-col>
          </div>
          <div v-else>
            <a-col :span="24">
              <a-form-model-item label="简介" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                <a-textarea placeholder="请输入简介" v-model="model.content" :autoSize="{ minRows: 4 }" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="从业资格证" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attachment" >
                <j-image-upload v-model="model.attachment"  isMultiple :number="imgMaxNumber"></j-image-upload>
                <div>最多上传 <span style="color: #f5222d;">{{ imgMaxNumber }}</span> 张照片</div>
              </a-form-model-item>
            </a-col>
          </div>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction,postAction,deleteAction,getFileAccessHttpUrl } from '@/api/manage'
  import { validateDuplicateValue,randomUUID} from '@/utils/util'
  const uidGenerator=()=>{
    return '-'+parseInt(Math.random()*10000+1,10);
  }
  export default {
    name: 'SkPublicInfoForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model:{
         },
        imgMaxNumber:5,
        labelCol: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        confirmLoading: false,
        validatorRules: {
          title: [
            { required: true, message: '请输入!'},
          ],
          type: [
            { required: true, message: '请输入公示类型!'},
          ],
          content: [
            { required: true, message: '请输入内容!'},
          ],
          attachment: [
            { required: true, message: '请上传从业资格证!'},
          ],
        },
        url: {
          add: "/family/skPublicInfo/add",
          edit: "/family/skPublicInfo/edit",
          queryById: "/family/skPublicInfo/queryById"
        },
        fileList:[]
      }
    },
    watch:{
      "model.type"(val){
        this.$refs.form.clearValidate();
        if (this.model.title) {
          if (this.model.type == 3 && this.model.title.length > 10 ) {
            this.model.title = this.model.title.substring(0,10)
          }
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.fileList = []
        this.model = Object.assign({}, record);
        this.visible = true;
        if (this.model.id && this.model.type  != 3 ) {
          this.model.baseId = this.model.id;
          if (this.model.files) {
            this.model.files.forEach(item => {
              this.handleFile(item)
            });
          }
        }
        if (!this.model.id) {
          this.model.baseId = randomUUID();
        }
        console.log(this.model.baseId,"'baseId'");
      },
      beforeUpload(file){
        console.log(file);
        const url = "/sys/oss/file/upload"
        let formData = new FormData();
        formData.append("file",file)
        formData.append("biz","temp")
        formData.append("baseId",this.model.baseId)
        postAction(url,formData).then((res)=>{
          if(res.success){
            this.handleFile(res.result)
          } else {
            this.$message.warning(res.message);
          }
        }).catch((error)=>{
          console.error(error);
        })
      },
      onRemove(e){
        console.log(e);
        const url = "/sys/oss/file/delete"
        const params = {
          id:e.id
        }
        deleteAction(url,params).then((res)=>{
          if(res.success){
            let fileIndex = this.fileList.findIndex(item=>item.url == e.url)
            this.fileList.splice(fileIndex,1)
          } else {
            this.$message.warning(res.message);
          }
        }).catch((error)=>{
          console.error(error);
        })
      },
      handleFile(result){
        this.fileList.push(
          {
            id:result.id?result.id:result.baseId,
            uid:uidGenerator(),
            name:result.fileName,
            status: 'done',
            url: getFileAccessHttpUrl(result.url),
            response:{
              status:"history",
              message:result.url
            }
          }
        )
      },
      
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              this.model.id = this.model.baseId;
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
         
        })
      },
    }
  }
</script>